package com.oa.core.utils.request;

import lombok.Data;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Data
public class RFormParam extends RParam {

    private HttpServletRequest request;

    private Map paramMap;

    public RFormParam() {
        super.setPageNum(0);
        super.setPageNum(10);
    }

    public RFormParam(HttpServletRequest request) {
        this.request = request;
        this.setPageNum(Integer.valueOf(request.getParameter("pageNum") == null ? "1" : request.getParameter("pageNum")));
        this.setPageSize(Integer.valueOf(request.getParameter("pageSize") == null ? "10" : request.getParameter("pageSize")));
    }

    @Override
    public String getString(String key) {
        return request.getParameter(key);
    }

    public Map getParamList() {
        if(paramMap != null){
            return paramMap;
        }

        Map properties = this.getRequest().getParameterMap();
        Iterator entries = properties.entrySet().iterator();

        Map returnMap = new HashMap();

        Map.Entry entry;
        String name = "";
        String value = "";

        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

    @Override
    public boolean paramExist(String ... key){
        for(String temp: key){
            if(getParamList().containsKey(temp) == false){
                return false;
            }
        }
        return true;
    }
}
